import {defineStore} from 'pinia';


export const useUserStore = defineStore('user', {
    state: () => ({
        isLoggedIn: !!localStorage.getItem('authToken'),
        authToken: localStorage.getItem('authToken') || null,
        username: localStorage.getItem('username') || '',
        csrfToken: localStorage.getItem('csrftoken') || null,
    }),
    actions: {
        // 新增CSRF令牌处理方法
        async fetchCSRFToken() {
            try {
                const response = await axios.get('/api/accounts/get_csrf_token/');
                this.csrfToken = response.data.csrfToken;
                localStorage.setItem('csrftoken', this.csrfToken);
                axios.defaults.headers.common['X-CSRFToken'] = this.csrfToken;
            } catch (error) {
                console.error('获取CSRF令牌失败:', error);
            }
        },
        checkLoginStatus() {
            const token = localStorage.getItem('authToken');
            const storedUsername = localStorage.getItem('username');

            if (token) {
                this.isLoggedIn = true;
                this.authToken = token;
                this.username = storedUsername || '用户';
            }
        },
        setAuthInfo(token, username) {// 登录成功后设置用户信息，第三方登录成功后调用
            localStorage.setItem('authToken', token);
            localStorage.setItem('username', username);

            this.authToken = token;
            this.username = username;
            this.isLoggedIn = true;
        },


        clearAuthInfo() {// 退出登录
            localStorage.removeItem('authToken');
            localStorage.removeItem('username');
            localStorage.removeItem('csrftoken');
            this.isLoggedIn = false;
            this.authToken = null;
            this.username = '';
            delete axios.defaults.headers.common['Authorization'];
            delete axios.defaults.headers.common['X-CSRFToken'];
        },
        logout() {
            this.clearAuthInfo();
        }
    }
});
